package com.atguigu.tingshu.search.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * Feign请求拦截器配置
 * 用于在Feign调用时传递userId请求头
 */
public class FeignClientConfig implements RequestInterceptor {
    public void apply(RequestTemplate requestTemplate) {
        // 获取请求对象
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (null != requestAttributes) {
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
            HttpServletRequest request = servletRequestAttributes.getRequest();
            String userId = request.getHeader("userId");
            requestTemplate.header("userId", userId);
        }
    }
}
